using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Media;
using System.Threading;
using System.Configuration;

namespace Wootbar
{
  public partial class frmMain : ShellLib.ApplicationDesktopToolbar
  {
    frmImage frm = new frmImage();
    private Woot Woot = new Woot();
    private string Key = KeyHelper.GetKey(String.Concat(Application.StartupPath, @"\", Application.ProductName, ".wbu"));
    private List<Woot> CachedWoots = new List<Woot>();

    public frmMain()
    {
      InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
      try
      {
        DockIt(Properties.Settings.Default.AppDockStatus == 1 ? AppBarEdges.Top : AppBarEdges.Bottom);
        if (Properties.Settings.Default.WootOffSleep)
          GotoSleep(false);

        SetAnimationState();
        OnlineStatus(true);
        backgroundWorker1.RunWorkerAsync();
      }
      catch (Exception) { }
    }

    private void PopulateForm()
    {
      try
      {
        /* don't update if we do not have data
         * if the title is blank treat it as if
         * nothing changed. Sometimes there is
         * latency that causes the data to be pulled with bad data
         */
        if (Woot.ItemTitle.Length > 0)
        {
          if (!CachedWoots.Exists(c => c.ItemTitle == Woot.ItemTitle))
          {
            this.CachedWoots.Add(Woot);
            TriggerAlerts();
          }

          // hide/show woot-off only feature
          tsCachedWoots.Visible = Woot.IsWootOff;

          // set basic labels
          lblItemInfo.Text = Woot.ItemTitle;
          lblCondition.Text = Woot.ItemCondition;
          lblPrice.Text = Woot.ItemPrice;
          lblQty.Text = "In-Stock";
          if (Woot.ItemQty > 0)
            lblQty.Text = string.Concat(Woot.ItemQty.ToString(), "%");

          // check for woot-off
          if (Woot.IsWootOff)
          {
            WakeUp();
          }
          // if item sold out display same message for woot/woot-off
          if (Woot.ItemSoldOut)
            lblQty.Text = "Sold Out!";
        }
      }
      catch (Exception) { }
    }

    private void TriggerAlerts()
    {
      // trigger alerts if required					
      if (Properties.Settings.Default.AlertNew)
        PlaySound(Application.StartupPath + "\\newalert.wav");

      string[] values = Properties.Settings.Default.MatchString.Split(',');
      foreach (string match in values)
      {
        if (match.Length > 0)
        {
          string tmpTitle = Woot.ItemTitle.ToLower();
          if (tmpTitle.Contains(match.ToLower()))
          {
            if (Properties.Settings.Default.AppAlert)
              PlaySound(Application.StartupPath + "\\alert.wav");

            if (Properties.Settings.Default.AppLaunchBuy)
            {
              try
              {
                System.Diagnostics.Process.Start(Woot.ItemPurchaseUrl);
              }
              catch (Exception) { };
            }
            break;
          }
        }
      }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
      try
      {
        if (!Woot.IsWootOff)
        {
          if (!backgroundWorker1.IsBusy)
            backgroundWorker1.RunWorkerAsync();
           }
        else
        {
          // fetch woot info                        
          if (!backgroundWorker1.IsBusy)
            backgroundWorker1.RunWorkerAsync();
        }
      }
      catch (Exception) { }
    }
    private void firsttimerun()
    {
      Installed();
      StartProcess("http://www.wootbar.net/installed.html");
    }

    private void DockIt(AppBarEdges pEdge)
    {
      this.Edge = pEdge;
      Properties.Settings.Default.AppDockStatus = (int)pEdge;
      Properties.Settings.Default.Save();
    }

    private void PlaySound(string strWavPath)
    {
      try
      {
        SoundPlayer simpleSound = new SoundPlayer(strWavPath);
        simpleSound.Play();
      }
      catch (Exception) { };
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
    {
      // update users online
      OnlineStatus(false);
    }

    private void StartProcess(string Proc)
    {
      try
      {
        System.Diagnostics.Process.Start(Proc);
      }
      catch { };
    }

    private void notifyIcon1_Click(object sender, EventArgs e)
    {
      WakeUp();
    }

    private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
    {
      WakeUp();
    }

    private void WakeUp()
    {
      if (!this.Visible)
      {
        this.Visible = true;
        DockIt(AppBarEdges.Float);
        switch (Properties.Settings.Default.AppDockStatus)
        {
          case 1:
            DockIt(AppBarEdges.Top);
            break;
          case 2:
            DockIt(AppBarEdges.Bottom);
            break;
          default:
            DockIt(AppBarEdges.Bottom);
            break;
        }
      }
    }

    private void GotoSleep(bool ShowBalloon)
    {
      DockIt(AppBarEdges.Float);
      this.Visible = false;
      notifyIcon1.Visible = true;
      if (ShowBalloon)
        notifyIcon1.ShowBalloonTip(5, "Wootbar.net", "Wootbar is catching some ZzZzZ's. If it detects a woot-off, it will spring into action like a naked superhero and become visible again. If this was an accident click this balloon.", ToolTipIcon.Info);
    }

    private void Installed()
    {
      //update installed count
      WebHelper.GetRawData(string.Concat("http://www.wootbar.net/installed.php?id=", Key));
    }

    private void OnlineStatus(bool online)
    {
      //update their status                									
      WebHelper.GetRawData(
          string.Concat("http://www.wootbar.net/online.php?id=", Key, "&status=", (online == true ? 0 : 1)));
    }

    private void lblWootbar_Click(object sender, EventArgs e)
    {
      StartProcess("http://www.wootbar.net");
    }

    private void lnkWootcom_Click(object sender, EventArgs e)
    {
      //StartProcess(this.Woot.ItemPurchaseUrl);
      StartProcess("http://www.woot.com");
    }

    private void 
      
      donateToolStripMenuItem_Click(object sender, EventArgs e)
    {
      StartProcess("http://www.wootbar.net/donate.html");
    }

    private void contToolStripMenuItem_Click(object sender, EventArgs e)
    {
      StartProcess("mailto:admin@wootbar.net?subject=" + string.Format("{0} {1}", Properties.Settings.Default.AppName, Properties.Settings.Default.AppVersion));
    }

    private void topToolStripMenuItem_Click(object sender, EventArgs e)
    {
      DockIt(AppBarEdges.Float);
      DockIt(AppBarEdges.Top);
    }

    private void bottomToolStripMenuItem_Click(object sender, EventArgs e)
    {
      DockIt(AppBarEdges.Float);
      DockIt(AppBarEdges.Bottom);
    }

    private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      settings frm = new settings();
      frm.ShowDialog();
      SetAnimationState();
    }

    private void sleepUntilWootoffToolStripMenuItem_Click(object sender, EventArgs e)
    {
      // snooze until woot off is detected.
      Properties.Settings.Default.AlertNew = true;
      Properties.Settings.Default.Save();
      GotoSleep(true);
    }

    private void closeToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void lblItemInfo_Click(object sender, EventArgs e)
    {

    }

    private void tsCachedWoots_Click(object sender, EventArgs e)
    {
      try
      {
        ddlPastWoots.Items.Clear();
        foreach (Woot w in this.CachedWoots)
        {
          ddlPastWoots.Items.Insert(0, w.ItemTitle);
        }
        if (ddlPastWoots.Items.Count > 0)
          ddlPastWoots.SelectedIndex = 0;
      }
      catch (Exception)
      {
      }
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      PopulateForm();
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
      Woot tmpWoot = new Woot();
      if (tmpWoot.ItemQty > 0 || tmpWoot.ItemSoldOut || tmpWoot.ItemTitle != this.Woot.ItemTitle)
        this.Woot = tmpWoot;

    }



    private void lblItemInfo_MouseEnter(object sender, EventArgs e)
    {
      try
      {
        if (Properties.Settings.Default.ShowImage)
        {
          frm.imgWootItem.ImageLocation = Woot.ItemImageUrl;
          frm.Refresh();
          frm.Show(this);
        }
      }
      catch { };
    }

    private void lblItemInfo_MouseLeave(object sender, EventArgs e)
    {
      if (Properties.Settings.Default.ShowImage)
        frm.Hide();
    }

    private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

    }
    private void SetAnimationState()
    {
      tsCachedWoots.Image = Properties.Settings.Default.AnimatedAlert ? Wootbar.Properties.Resources.gold_light : Wootbar.Properties.Resources.gold_lightNoAnimation;
    }

    private void tsOption_Click(object sender, EventArgs e)
    {

    }

    private void checkForUpdateToolStripMenuItem_Click(object sender, EventArgs e)
    {
      int CurrentVersion = Properties.Settings.Default.AppVersionNumeric;
      try
      {
        string AvailableVersion = WebHelper.GetRawData("http://www.wootbar.net/version.html");
        if (Convert.ToInt16(AvailableVersion) > CurrentVersion)
        {
          DialogResult dr = MessageBox.Show(string.Format("{0}\n{1}{2}\n{3}{4}\n\n{5}",
              "There is an upgrade available!", "Your version:", CurrentVersion.ToString(), "Current Version:", AvailableVersion, "Do you want to download the upgrade?"), "Upgrade Available", MessageBoxButtons.YesNo);
          if (dr == DialogResult.Yes)
          {
            MessageBox.Show(this, "Close wootbar before you run the new upgrade setup.", "Upgrade.", MessageBoxButtons.OK);
            StartProcess("http://www.wootbar.net/downloads/wootbar_installer.msi");
          }
        }
        else
        {
          DialogResult dr = MessageBox.Show(string.Format("{0}",
             "There is NO upgrade available", MessageBoxButtons.OK));
        }
      }
      catch (Exception)
      {
        MessageBox.Show(this, "Failed checking for update! Please visit http://www.wootbar.net/downloads",
            string.Format("{0} {1}", Properties.Settings.Default.AppName, CurrentVersion), MessageBoxButtons.OK);
      }
    }
  }
}